package com.topisv.tms.web.work;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.lightShelf.LightShelf;
import com.topisv.tms.entity.pickCar.PickCar;
import com.topisv.tms.entity.pickCar.PickCarStock;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.entity.work.WorkTask;
import com.topisv.tms.entity.work.WorkTaskItem;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.lightShelf.LightShelfService;
import com.topisv.tms.service.pickCar.PickCarService;
import com.topisv.tms.service.pickCar.PickCarStockService;
import com.topisv.tms.service.vo.WorkOrderInfoVo;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.service.work.WorkTaskItemService;
import com.topisv.tms.service.work.WorkTaskService;
import com.topisv.tms.tools.ExcelUtils;
import com.topisv.tms.utils.JsonUtil;

/**
 * 拣货任务_control
 * @author ch
 */
@Controller
@RequestMapping({ "/pickTask" })
public class PickTaskController {

	private static final Logger logger = LoggerFactory.getLogger(PickTaskController.class);

	@Autowired
	private WorkOrderService workOrderService;
	@Autowired
	private WorkTaskService workTaskService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private PickCarService pickCarService;
	@Autowired
	private PickCarStockService workCarStockService;
	@Autowired
	private LightShelfService lightShelfService;
	@Autowired
	private WorkTaskItemService workTaskItemService;
	
	/**
	 * 导向拣货任务列表页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "v2_toPickTaskListPage")
	public String toPickTaskListPage(ServletRequest request,HttpServletResponse response,Model model){
		try {
			
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			 model.addAttribute("loginerId", curUser.id);
		    //查找我的拣货任务
		    Map<String, Object> param_my=new HashMap<String, Object>();
		    param_my.put("pickerId", curUser.id);
		    param_my.put("status", "2"); //任务状态( 1.创建任务 2.已分配拣货任务 3.单据上架（灯光架、拣货车） 4.已拣货 5.已分配包装任务  6.已包装 7.已分配发货任务 8.已发货)
		    List<WorkTask> myPickTaskList=this.workTaskService.loadTaskByParam(param_my);
		    model.addAttribute("myPickTaskList",myPickTaskList);
		    
		    Subject subject = SecurityUtils.getSubject();
		    Session session = subject == null ? null : subject.getSession();
	
		    String customerCodeP = null;
		    String warehouseCodeP = null;
		    if (session != null) {
		        customerCodeP = (String) session.getAttribute("pickTaskController.customerCode");
		        warehouseCodeP = (String) session.getAttribute("pickTaskController.warehouseCode");
		    }
		    String taskCode = request.getParameter("_taskCode");
		    
		    //如果是paiu用户,初始化数据
			if("paiu".equals(curUser.userType)){
				//未分配的拣货任务
			    /** begin add 20161107 默认不查询待分配的任务，只有当手动点击按钮时查询 且 商家、任务编号必选其一 */
			    Map<String, Object> param_untaked=new HashMap<String, Object>();
			    param_untaked.put("customerCodes", StringUtils.isNotBlank(customerCodeP) ? customerCodeP : (StringUtils.isBlank(curUser.customers)?"blank":curUser.customers));
			    param_untaked.put("areagroups", StringUtils.isNotBlank(warehouseCodeP) ? warehouseCodeP : (StringUtils.isBlank(curUser.areagroups)?"blank":curUser.areagroups));
			    param_untaked.put("status", "1"); //任务状态( 1.创建任务 2.已分配拣货任务 3.单据上架（灯光架、拣货车） 4.已拣货 5.已分配包装任务  6.已包装 7.已分配发货任务 8.已发货)
			    
			    if (StringUtils.isNotBlank(customerCodeP) || StringUtils.isNotBlank(taskCode)) {
			        List<WorkTask> untakedPickTaskList=this.workTaskService.loadTaskByParam(param_untaked);
			        model.addAttribute("untakedPickTaskList",untakedPickTaskList);
			    } else {
			        model.addAttribute("_manualSearchTip", "<-点击查询(选填商家或任务编号)，显示2000条");
			    }
			    
			    /** end add 20161107 默认不查询待分配的任务，只有当手动点击按钮时查询 且 商家、任务编号必选其一 */
			    
	            model.addAttribute("_customerCode", customerCodeP);
	            model.addAttribute("_warehouseCode", warehouseCodeP);
	            
	            if (StringUtils.isNotBlank(customerCodeP)) {
	                List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser, customerCodeP);
	                model.addAttribute("warehouseList", warehouseList);
	            }
			}
		    
		    //如果是商家用户,初始化数据
			if("customer".equals(curUser.userType)){
				
				String customerCode=customerList.get(0).getCustomerCode();
				model.addAttribute("_customerCode",customerCode);
				
				//初始化仓库数据
				List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
				model.addAttribute("warehouseList", warehouseList);
				
				//未分配的拣货任务
                Map<String, Object> param_untaked=new HashMap<String, Object>();
                param_untaked.put("customerCodes", customerCode);
                param_untaked.put("status", "1"); //任务状态( 1.创建任务 2.已分配拣货任务 3.单据上架（灯光架、拣货车） 4.已拣货 5.已分配包装任务  6.已包装 7.已分配发货任务 8.已发货)
                
                List<WorkTask> untakedPickTaskList=this.workTaskService.loadTaskByParam(param_untaked);
                model.addAttribute("untakedPickTaskList",untakedPickTaskList);
			}
		
		} catch (Exception e) {
			
			logger.error("error",e);
		}
	    
		return "work/pick/pickTaskList";
	}
	
	
	/**
	 * 查询拣货任务列表
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "v2_queryPickTaskList")
	public String queryPickTaskList(Model model, ServletRequest request, ServletResponse response) throws Exception {
		try {
		
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			//查找我的拣货任务
		    Map<String, Object> param_my=new HashMap<String, Object>();
		    param_my.put("pickerId", curUser.id);
		    param_my.put("status", "2"); //任务状态( 1.创建任务 2.已分配拣货任务 3.单据上架（灯光架、拣货车） 4.已拣货 5.已分配包装任务  6.已包装 7.已分配发货任务 8.已发货)
		    List<WorkTask> myPickTaskList=this.workTaskService.loadTaskByParam(param_my);
		    model.addAttribute("myPickTaskList",myPickTaskList);
			
		    //查询未分配的拣货任务
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			
			/** begin add 20161107 默认不查询待分配的任务，只有当手动点击按钮时查询 且 商家、任务编号必选其一 */
			String manualSearch = (String) param.get("manualSearch");
			String taskCode=(String) param.get("taskCode");
			String customerCode=(String) param.get("customerCode");
			
			if (manualSearch == null || (StringUtils.isBlank(taskCode) && StringUtils.isBlank(customerCode))) {
			    model.addAttribute("_manualSearchTip", "<-点击查询(选填商家或任务编号)，显示2000条");
			    return "work/pick/pickTaskList";
			}
			/** end add 20161107 默认不查询待分配的任务，只有当手动点击按钮时查询 且 商家、任务编号必选其一 */
			
			String batchType=(String) param.get("batchType");
			String pickType=(String) param.get("pickType");
			String warehouseCode=(String) param.get("warehouseCode");
			
    
			//add 11.11
			Subject subject = SecurityUtils.getSubject();
			Session session = subject == null ? null : subject.getSession();
			
            /*if (StringUtils.isBlank(customerCode)) {
                if (session != null)
                    customerCode = (String) session.getAttribute("pickTaskController.customerCode");
            }
            if (StringUtils.isBlank(warehouseCode)) {
                if (session != null)
                    warehouseCode = (String) session.getAttribute("pickTaskController.warehouseCode");
            }*/
			
			if(StringUtils.isBlank(customerCode)){
				param.put("customerCodes", this.customersService.loadCustomerByAuthority(curUser.jobuuid));
			}else{
				param.put("customerCodes", customerCode);
			}
			
			if(StringUtils.isBlank(warehouseCode)){
				param.put("areagroups", curUser.areagroups);
			}else{
				param.put("areagroups", warehouseCode);
			}
			
			param.put("batchType", batchType);
			param.put("pickType", pickType);
			
			param.put("status", "1"); //任务状态( 1.创建任务 2.已分配拣货任务 3.单据上架（灯光架、拣货车） 4.已拣货 5.已分配包装任务  6.已包装 7.已分配发货任务 8.已发货)
			
			// begin 增加任务编号查询条件 by rongfei.zhang
			if(StringUtils.isNotBlank(taskCode)){
				param.put("taskCode", taskCode);
			}
			model.addAttribute("_taskCode", taskCode);
			// end 增加任务编号查询条件 by rongfei.zhang
			
			List<WorkTask> untakedPickTaskList = this.workTaskService.loadTaskByParam(param);
			model.addAttribute("untakedPickTaskList", untakedPickTaskList);
			model.addAttribute("_warehouseCode", warehouseCode);
			model.addAttribute("_customerCode", customerCode);
			
			//add 11.11
			if (session != null) {
		        session.setAttribute("pickTaskController.customerCode", customerCode);
		        session.setAttribute("pickTaskController.warehouseCode", warehouseCode);
			}

			//初始化仓库数据
			if(StringUtils.isNotBlank(customerCode)){
				List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
				model.addAttribute("warehouseList", warehouseList);
			}
		
		} catch (Exception e) {
			
			logger.error("error",e);
		}

		return "work/pick/pickTaskList";
	}
	
	
	/**
	 * 导向拣货页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_toPickTaskPage/{taskId}", method = RequestMethod.GET)
	public String toPickTaskPage(@PathVariable("taskId") Long taskId, Model model) {
		try {

		    WorkTask  task=this.workTaskService.loadTaskById(taskId);
		    model.addAttribute("task", task);
		    
		    //查询空置灯光架
		    List<LightShelf> lightShelfList=this.lightShelfService.loadLightShelf(task.getWarehouseCode(),"free");
		    model.addAttribute("lightShelfList", lightShelfList);
		    
		    //查询空置推车
		    List<PickCar> carList=this.pickCarService.loadCar(task.getCustomerCode(),task.getWarehouseCode(),"free");
		    model.addAttribute("carList", carList);
		    
		    //查询任务订单
		    Map<String, Object> param=new HashMap<String, Object>();
		    param.put("taskCode", task.getTaskCode());
		    List<WorkOrder> orderList=this.workOrderService.loadOrder(param);
		    model.addAttribute("orderList", orderList);
		    
		    String workType=task.getPickType();
		    if("single".equals(workType)){//单件
		        //modify 2016-05-04 单件订单可选择推车拣选，且使用多件订单拣选页面
		        if ("car".equals(task.getPickModel())) {
                    return "work/pick/pickTask_multi";
		        }
		        
		    	return "work/pick/pickTask_single";
		    }else if("multi".equals(workType)){//多件
		    	return "work/pick/pickTask_multi";
		    }
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return null;
	}
	
	/**
	 * 领取拣货任务
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxTakePickTask")
	@ResponseBody
	public String ajaxTakePickTask(ServletRequest request,HttpServletResponse response) {
	    boolean isLockSuccess = false;
	    Long taskId=Long.valueOf(request.getParameter("taskId")+""); 
		try {	
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			
			isLockSuccess = workTaskService.lock("ajaxTakePickTask", taskId+"", "-");
            if (!isLockSuccess) {
                return "false";
            }
            
			this.workTaskService.takeTask(taskId,curUser.id,"pick");
			return "true";
		} catch (Exception e) {
			logger.error("error",e);
			return "false";
		} finally {
            if (isLockSuccess) {
                workTaskService.releaseLock("ajaxTakePickTask", taskId+"");
            }
        }
	}
	
	/**
	 * 完成拣货任务
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxCompletePickTask")
	@ResponseBody
	public String ajaxCompletePickTask(ServletRequest request,HttpServletResponse response) {
		try {	
			String taskCode=request.getParameter("taskCode"); 
			
			this.workTaskService.pickAll(taskCode);
			return "true";
		} catch (Exception e) {
			logger.error("error",e);
			return "false";
		}
	}	
	
	/**
	 * 导向单据上拣货车页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toPickCar/{taskId}", method = RequestMethod.GET)
	public String toPickCar(@PathVariable("taskId") Long taskId, Model model) {
		try {

			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		    String customerCode=curUser.customerCode;
		    Customers customer=this.customersService.findByCustomerCode(customerCode);
		    model.addAttribute("customer", customer); 
		    
		    WorkTask  task=this.workTaskService.loadTaskById(taskId);
		    model.addAttribute("task", task);
		    String warehouseCode=task.getWarehouseCode();
		    
		    //查询空置作业车
		    List<PickCar> pickCarList=this.pickCarService.loadCar(customerCode,warehouseCode,"free");
		    model.addAttribute("pickCarList", pickCarList);
		    
		   //查询未入车的订单信息
		    Map<String, Object> param=new HashMap<String, Object>();
		    param.put("taskCode", task.getTaskCode());
		    param.put("billStatus", "0");
		    List<WorkOrder> orderList=this.workOrderService.loadOrder(param);
		    model.addAttribute("orderList", orderList);
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "work/pick/bill2car";
	}
	
	
	/**
	 * 导向单据上灯光架页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toLightShelf/{taskId}", method = RequestMethod.GET)
	public String toLightShelf(@PathVariable("taskId") Long taskId, Model model) {
		try {

			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		    String customerCode=curUser.customerCode;
		    Customers customer=this.customersService.findByCustomerCode(customerCode);
		    model.addAttribute("customer", customer); 
		    
		    WorkTask  task=this.workTaskService.loadTaskById(taskId);
		    model.addAttribute("task", task);
		    String warehouseCode=task.getWarehouseCode();
		    
		    //查询空置灯光架
		    List<LightShelf> lightShelfList=this.lightShelfService.loadLightShelf(warehouseCode,"free");
		    model.addAttribute("lightShelfList", lightShelfList);
		    
		   //查询未上架订单信息
		    Map<String, Object> param=new HashMap<String, Object>();
		    param.put("taskCode", task.getTaskCode());
		    param.put("billStatus", "0");
		    List<WorkOrder> orderList=this.workOrderService.loadOrder(param);
		    model.addAttribute("orderList", orderList);
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "work/pick/bill2lightshelf";
	}
	
	
	/**
	 * ajax查询拣货车信息
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxGetPickCarStockInfo")
	public String ajaxGetPickCarStockInfo(ServletRequest request,HttpServletResponse response) {
		try {
		String taskCode=request.getParameter("taskCode");
		Long carId=Long.valueOf(request.getParameter("carId"));
		
		Map<String,Object> map = new HashMap<String,Object>();
		
		//推车
		PickCar car=this.pickCarService.loadPickCarById(carId);
		map.put("car", car);
		
		//车位信息
		List<PickCarStock> stockList=this.workCarStockService.loadStockByCarId(carId);
		map.put("stockList", stockList);
		
		//订单信息
		Map<String, Object> param=new HashMap<String, Object>();
	    param.put("taskCode",taskCode);
	    param.put("billStatus", "0");
	    List<WorkOrder> orderList=this.workOrderService.loadOrder(param);
	    map.put("orderList", orderList);
		
		
		String json = JsonUtil.getObjectString(map);
		PrintWriter out;
		out = response.getWriter();
		out.print(json);
		
		} catch (Exception e) {
			logger.error("error",e);
		}
		return null;
	}
	
	
	/**
	 * 导向打印拣货单页面_多件
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_toPrintPickInfo_multi/{taskCode}", method = RequestMethod.GET)
	public String toPrintPickInfo_multi(@PathVariable("taskCode") String taskCode, Model model) {
		try {
			//任务信息
			WorkTask task=this.workTaskService.loadTaskByCode(taskCode);
			model.addAttribute("task",task);
			
			//拣货信息
			List<Map.Entry<String,Integer>> printInfoList=this.workTaskService.loadPrintInfo_multi(taskCode);
		    model.addAttribute("printInfoList",printInfoList);
		    
		} catch (Exception e) {
			logger.error("error",e);
		}
		return "work/pick/printPickInfo_multi";
	}
	
	/**
	 * 导出拣货单_多件
	 */
	@RequestMapping(value = "exportExcel_multi/{taskCode}")
	public String exportExcel_multi(@PathVariable("taskCode") String taskCode, Model model, ServletRequest request,ServletResponse response){
		FileInputStream f=null;
		OutputStream output=null;
		try {
			
			Date now=new Date();
			DateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
			
			//任务信息
			WorkTask task=this.workTaskService.loadTaskByCode(taskCode);
			int flag=0;
			if(task.getPickModel().equals("car")){
				flag=1;
			}
			model.addAttribute("task",task);
			
			//拣货信息
			/*List<Map.Entry<String,Integer>> printInfoList=this.workTaskService.loadPrintInfo_multi(taskCode);
		    model.addAttribute("printInfoList",printInfoList);*/
		    
		    Map<String, Object> param1=new HashMap<String, Object>();
			param1.put("taskCode", taskCode);
			List<WorkTaskItem> taskItemList=this.workTaskItemService.loadByParam(param1);
			
			/** 定义导出数据集合 */
			List<Object[]> list = new ArrayList<Object[]>();
			
			/*String stockCode,boxCode,sku;
			String[] stockInfoSplit;
			Integer num;*/
			
			for (int i = 0; i < taskItemList.size(); i++) {
				try {
				
				WorkTaskItem info=taskItemList.get(i);
				if(flag==1){
					info.setAllocationDetail(getDetail(getStockInfo(info), loadWorkOrderLike(info)));
				}else{
					info.setAllocationDetail("");
				}
				/*stockInfoSplit=info.getKey().split("_");
				stockCode=stockInfoSplit[0];
				boxCode=stockInfoSplit[1];
				sku=stockInfoSplit[2];
				num=info.getValue();*/
				
				Object[] obj = {
						i+1,
						info.getCustomerCode(),
						info.getWarehouseCode(),
					    info.getStockCode(),
					    info.getBoxCode(),
					    info.getSku(),
					    info.getSkuName(),
					    (Integer)info.getNum(),
					    info.getAllocationDetail(),
					    "",
					    null
				};
				list.add(obj);
				
				} catch (Exception e) {
					
					logger.error("error",e);
				}
				
			}
			Object[] obj = {
					null,
					null,
					null,
					null,
					null,
					null,
					null,
				    task.getGoodsNum(),
				    null,
				    "",
				    null
			};
			list.add(obj);
			/** 导出数据 */
			String[] title = { "序号", "商家","仓库","库位", "箱位","sku","sku名称", "数量","箱位指引","备注"};
			String filepath = "拣货单_"+task.getTaskCode()+".xls";
			String title_page="拣货单（任务编号："+task.getTaskCode()+"）";
			ExcelUtils.writeExcel(title, filepath,title_page, df.format(now) , list); // 生成excel
			
			/** 把生成的excel文件读出字节返回给客户端 */
			((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename="+ new String(filepath.getBytes("gb2312"),"iso8859-1"));
			f = new FileInputStream(ExcelUtils.TEMPPATH+filepath);
			byte[] fb = new byte[f.available()];
			f.read(fb);
			ByteArrayInputStream bais = new ByteArrayInputStream(fb);
			output =((HttpServletResponse)response).getOutputStream();
			int by = 0;
			while ((by = bais.read()) != -1) {
				output.write(by);
			}
			output.flush();
			
		} catch (Exception e) {
			return "error";
		}finally{
			if (output!=null) {
				try { output.close(); } catch (IOException e) {logger.error("error",e);}
			}
			if (f!=null) {
				try { f.close(); } catch (IOException e)  {logger.error("error",e);}
			}
		}
		return null;
	}
	/**
	 * 根据任务编码、库位信息模糊查询workOrder
	 * @param workTaskItem
	 * @return
	 */
		private List<WorkOrder> loadWorkOrderLike(WorkTaskItem workTaskItem) {
			return workTaskService.loadWorkOrderLike(workTaskItem.getTaskCode(),getStockInfo(workTaskItem));
		}
	/**
	 * 根据箱位码、库位码、SKU拼装成箱位码_库位码_SKU
	 * @param workTaskItem
	 * @return
	 */
		private String getStockInfo(WorkTaskItem workTaskItem) {
			return new StringBuilder()
					.append(workTaskItem.getStockCode()).append("_")
					.append(workTaskItem.getBoxCode()).append("_")
					.append(workTaskItem.getSku()).toString();
		}
	/**
	 * 获取箱位指引
	 * @param stock_info
	 * @param workOrderList
	 * @return
	 */
		private String getDetail(String stock_info, List<WorkOrder> workOrderList) {
			StringBuilder detail=new StringBuilder();
			for(WorkOrder workOrder:workOrderList){
				for(int i=0;i<getStockInfoArr(workOrder).length;i++){
					if(StringUtils.equals(stock_info, getStockOneSub(workOrder, i))){
						detail.append(workOrder.getRankno()).append("(").append(getStockInfoOneNum(workOrder, i)).append(")");
					}
				}
			}
			return detail.toString();
		}
		/**
		 * 截取stockInfo,得到数量
		 * @param workOrder
		 * @param i
		 * @return
		 */
		private String getStockInfoOneNum(WorkOrder workOrder, int i) {
			return getStockInfoArr(workOrder)[i].substring(getStockInfoArr(workOrder)[i].lastIndexOf("_")+1);
		}
		/**
		 * 截取stockInfo,得到箱位码_库位码_SKU
		 * @param workOrder
		 * @param i
		 * @return
		 */
		private String getStockOneSub(WorkOrder workOrder, int i) {
			return getStockInfoArr(workOrder)[i].substring(0,getStockInfoArr(workOrder)[i].lastIndexOf("_"));
		}
		/**
		 * stockinfo 获取
		 * @param workOrder
		 * @return
		 */
		private String[] getStockInfoArr(WorkOrder workOrder) {
			return workOrder.getStockInfo().split(";");
		}
	
	
	/**
	 * 导向打印拣货单页面_单件
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_toPrintPickInfo_single/{taskCode}", method = RequestMethod.GET)
	public String toPrintPickInfo_single(@PathVariable("taskCode") String taskCode, Model model) {
		try {
			//任务信息
			WorkTask task=this.workTaskService.loadTaskByCode(taskCode);
			model.addAttribute("task",task);
			
			//拣货信息
			List<Map.Entry<String,Object>> printInfoList=this.workTaskService.loadPrintInfo_single(taskCode);
		    model.addAttribute("printInfoList",printInfoList);
		    
		} catch (Exception e) {
			logger.error("error",e);
		}
		return "work/pick/printPickInfo_single";
	}
	
	/**
	 * 导出拣货单_单件
	 */
	@RequestMapping(value = "exportExcel_single/{taskCode}")
	public String exportExcel_single(@PathVariable("taskCode") String taskCode, Model model, ServletRequest request,ServletResponse response){
		FileInputStream f=null;
		OutputStream output=null;
		try {
			
			Date now=new Date();
			DateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
			
			//任务信息
			WorkTask task=this.workTaskService.loadTaskByCode(taskCode);
			//String flowType=task.getFlowType();
			//model.addAttribute("task",task);
			
			//拣货信息
			//List<Map.Entry<String,Object>> printInfoList=this.workTaskService.loadPrintInfo_single(taskCode);
		   // model.addAttribute("printInfoList",printInfoList);
		    
			//拣货任务项
			Map<String, Object> param1=new HashMap<String, Object>();
			param1.put("taskCode", taskCode);
			List<WorkTaskItem> taskItemList=this.workTaskItemService.loadByParam(param1);
			
			/** 定义导出数据集合 */
			List<Object[]> list = new ArrayList<Object[]>();
			
			
			//if(flowType.equals("intimePrint")){ //及时打单
				
				for (int i = 0; i < taskItemList.size(); i++) {
					try {
					
					WorkTaskItem info=taskItemList.get(i);
					info.setAllocationDetail(getDetail(getStockInfo(info), loadWorkOrderLike(info)));
					
					Object[] obj = {
							i+1,
							info.getCustomerCode(),
							info.getWarehouseCode(),
						    info.getStockCode(),
						    info.getBoxCode(),
						    info.getSku(),
						    info.getSkuName(),
						    (Integer)info.getNum(),
						    info.getAllocationDetail(),
						    "",
						    null
					};
					list.add(obj);
					
					} catch (Exception e) {
						
						logger.error("error",e);
					}
					
				}
				Object[] obj = {
						null,
						null,
						null,
						null,
						null,
						null,
						null,
					    task.getGoodsNum(),
					    null,
					    "",
					    null
				};
				list.add(obj);
				/** 导出数据 */
				String[] title = { "序号", "商家","仓库","库位", "箱位","sku","sku名称", "数量","箱位指引","备注"};
				String filepath = "拣货单_"+taskCode+".xls";
				String title_page="拣货单（任务编号："+taskCode+"）";
				ExcelUtils.writeExcel(title, filepath,title_page, df.format(now) , list); // 生成excel
				
				/** 把生成的excel文件读出字节返回给客户端 */
				((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename="+ new String(filepath.getBytes("gb2312"),"iso8859-1"));
				f = new FileInputStream(ExcelUtils.TEMPPATH+filepath);
				byte[] fb = new byte[f.available()];
				f.read(fb);
				ByteArrayInputStream bais = new ByteArrayInputStream(fb);
				output =((HttpServletResponse)response).getOutputStream();
				int by = 0;
				while ((by = bais.read()) != -1) {
					output.write(by);
				}
				output.flush();
				
				
			//}
		} catch (Exception e) {
			return "error";
		}finally{
			if (output!=null) {
				try { output.close(); } catch (IOException e) {logger.error("error",e);}
			}
			if (f!=null) {
				try { f.close(); } catch (IOException e)  {logger.error("error",e);}
			}
		}
		return null;
	}
	
	/**
	 * 导向拣货页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_toPickPage/{taskCode}", method = RequestMethod.GET)
	public String toPickPage(@PathVariable("taskCode") String taskCode, Model model) {
		try {
			//任务信息
			WorkTask task=this.workTaskService.loadTaskByCode(taskCode);
			model.addAttribute("task",task);
			
			//拣货任务项
			Map<String, Object> param1=new HashMap<String, Object>();
			param1.put("taskCode", taskCode);
			List<WorkTaskItem> taskItemList=this.workTaskItemService.loadByParam(param1);
			model.addAttribute("taskItemList",taskItemList);
			
		} catch (Exception e) {
			logger.error("error",e);
		}
		return "work/pick/pick";
	}
	
	/**
	 * 拣货
	 * @param taskItemId 拣货项ID
	 * @param response
	 */
	@RequestMapping(value = "ajaxPick")
	public void ajaxPick(ServletRequest request,HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		
		Long taskItemId=Long.valueOf(request.getParameter("taskItemId"));
		String sku=request.getParameter("sku");
		
		boolean isLockSuccess = false;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			
			/** begin add bug:360. 防止重复操作的校验. 20160618, lianghe.yuan */
			isLockSuccess = workTaskService.lock("PickTaskController#ajaxPick", taskItemId + "", "-");
			
			if (!isLockSuccess) {
			    json.put("status", "error");
	            json.put("content", "当前任务已在处理中，请勿重复处理！");
	            
	            out.print(json.toString());
	            return;
			}
			/** end add bug:360. 防止重复操作的校验. 20160618, lianghe.yuan */
			
			
			//拣货
			String msg=this.workTaskService.pick(taskItemId,sku);
			json.put("status", msg);
			
		} catch (Exception e) {
			
			json.put("status","error");
			json.put("content",e.getMessage());
			logger.error("error",e);
		} finally {
			 if (isLockSuccess) {
			 	// add bug:360. 防止重复操作的校验. 操作完成，释放锁. 20160618, lianghe.yuan
				 workTaskService.releaseLock("PickTaskController#ajaxPick", taskItemId + "");
			}
		}
		out.print(json.toString());
	}
	
	/**
	 * 拣货_优化方法 by ch 20140402
	 * @param taskItemId 拣货项ID
	 * @param response
	 */
	@RequestMapping(value = "ajaxPick_1")
	public void ajaxPick_1(ServletRequest request,HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;

		Long taskItemId=Long.valueOf(request.getParameter("taskItemId"));
		String sku=request.getParameter("sku");
		
		boolean isLockSuccess = false;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			/** begin add bug:360. 防止重复操作的校验. 20160618, lianghe.yuan */
			isLockSuccess = workTaskService.lock("PickTaskController#ajaxPick_1", taskItemId + "", "-");
			
			if (!isLockSuccess) {
			    json.put("status", "error");
	            json.put("content", "当前任务已在处理中，请勿重复处理！");
	            
	            out.print(json.toString());
	            return;
			}
			/** end add bug:360. 防止重复操作的校验. 20160618, lianghe.yuan */

			String boxCode=request.getParameter("boxCode");
			
			//拣货
			String msg=this.workTaskService.pick(taskItemId,sku,boxCode);
			json.put("status", msg);
			
		} catch (Exception e) {
			
			json.put("status","error");
			json.put("content",e.getMessage());
			logger.error("error",e);
		} finally {
			if (isLockSuccess) {
			 	// add bug:360. 防止重复操作的校验. 操作完成，释放锁. 20160618, lianghe.yuan
				 workTaskService.releaseLock("PickTaskController#ajaxPick_1", taskItemId + "");
			}
		}
		out.print(json.toString());
	}

	
	/**
	 * 拣货绑定流转箱
	 * @param taskItemId 拣货项ID
	 * @param response
	 */
	@RequestMapping(value = "ajaxBindBox")
	public void ajaxBindBox(ServletRequest request,HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			String taskCode=request.getParameter("taskCode");
			String workBoxCode=request.getParameter("workBoxCode");
			
			//绑定流转箱
			String msg=this.workTaskService.bindBox(taskCode,workBoxCode);
			json.put("status", msg);
			
		} catch (Exception e) {
			
			json.put("status","error");
			json.put("content",e.getMessage());
			logger.error("error",e);
		}
		out.print(json.toString());
	}
	/**
	 * 打印拣货单
	 * @param taskCode
	 * @param response
	 */
	@RequestMapping(value="ajaxPrintPickInfo",method = RequestMethod.POST)
	public void ajaxPrintPickInfo(@RequestParam(value = "taskCode") String taskCode,
			HttpServletResponse response){
		PrintWriter out=null;
		JSONObject json=null;
		try {
			json=new JSONObject();
			out=response.getWriter();
			//拣货任务项
			Map<String, Object> param1=new HashMap<String, Object>();
			param1.put("taskCode", taskCode);
			List<WorkTaskItem> taskItemList=this.workTaskItemService.loadByParam(param1);
			List<WorkOrderInfoVo> InfoVo = new ArrayList<WorkOrderInfoVo>();
			if("MID".equals(taskItemList.get(0).getCustomerCode())){
				InfoVo = workOrderService.findPickDetail(taskCode);
				
			}
			WorkTask workTask=workTaskService.loadTaskByCode(taskCode);
			if(null!=workTask){
				workTaskService.updateTaskPrintFlag(taskCode, workTask.getPrintFlag()+1);
			}
			json.put("printFlag", (workTask.getPrintFlag()+1)+"");
			json.put("workOrderList", InfoVo);
			json.put("taskItemList", taskItemList);
			json.put("status","1");
			out.print(json.toString());
		} catch (IOException e) {
			json.put("status","0");
			e.printStackTrace();
		}
	}
}